import {
  Box,
  Checkbox,
  CheckboxGroup,
  Input,
  InputGroup,
  Stack,
  InputLeftAddon,
  InputRightAddon,
  FormHelperText,
  Button,
  FormControl,
  Menu,
  MenuButton,
  MenuList,
  MenuItem,
  Text,
  Image,
  Link,
  FormErrorMessage,
  useToast
} from '@chakra-ui/react';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import JInput from './JInput';

import WechatIcon from '../assets/images/icon-wechat.png';
import QQIcon from '../assets/images/icon-qq.png';
import WeiboIcon from '../assets/images/icon-weibo.png';
import LockIcon from '../assets/images/icon-lock.png';
import UserIcon from '../assets/images/icon-user.png';

import { login } from '../api/user';
import { useState } from 'react';

export default function SignIn() {
  const toast = useToast();
  const [ checked, setChecked ] = useState(false);
  const handleProblem = (key) => {
    const links = {
      'phone': {
        url: 'https://www.jianshu.com/users/password/mobile_reset',
        target: '_self'
      },
      'email': {
        url: 'https://www.jianshu.com/users/password/email_reset',
        target: '_self'
      },
      'foreign': {
        url: 'https://www.jianshu.com/p/9058d0b8711d',
        target: '_blank'
      },
      'google': {
        url: 'https://www.jianshu.com/p/498a9fa7da08',
        target: '_blank'
      }
    };
    const link = links[key];
    if (link.target === '_self') {
      window.location.href = link.url;
    } else {
      window.open(link.url);
    }
  }
  const formik = useFormik({
    initialValues: JSON.parse(window.localStorage.getItem('UserData'))||{ email: '', password: ''},
    validationSchema: Yup.object({
      email: Yup.string()
        .required('请填写用户名或邮箱'),
      password: Yup.string()
        .min(8, '密码的长度不能小于8')
        .required('请填写密码')
    }),
    onSubmit: async values => {
      try {
        const { data } = await login({
          user: values
        });
        toast({
          title: "提示信息",
          description: "登录成功！",
          status: "success",
          duration: 9000,
          isClosable: true,
          position: 'top-left'
        });
        if (checked) {
          window.localStorage.setItem('UserData', JSON.stringify(values));
        } else {
          window.localStorage.removeItem('UserData');
        }
      } catch (e) {
        toast({
          title: "提示信息",
          description: "登录失败！",
          status: "error",
          duration: 9000,
          isClosable: true,
          position: 'top-left'
        });
      }
    }
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <Stack spacing={0} border="1px solid #c8c8c8">
        <FormControl isRequired  isInvalid={formik.errors.email && formik.touched.email}>
          <InputGroup bg="#f7f7f7" borderBottom="1px solid #c8c8c8">
            <InputLeftAddon children={<Image src={UserIcon} w="18px" he="25px"/>} borderRadius="0" bg="inherit" h="50px" border="none" px="8px"/>
            <JInput placeholder="用户名或邮箱" {...formik.getFieldProps('email')} required={false}/>
          </InputGroup>
          <FormErrorMessage>{ formik.errors.email }</FormErrorMessage>
        </FormControl>
        <FormControl isRequired  isInvalid={formik.errors.password && formik.touched.password}>
          <InputGroup bg="#f7f7f7" >
            <InputLeftAddon children={<Image src={LockIcon} w="18px" he="25px"/>} borderRadius="0" bg="inherit" h="50px" border="none" px="8px"/>
            <JInput placeholder="密码" type="password" {...formik.getFieldProps('password')} required={false}/>
          </InputGroup>
          <FormErrorMessage>{ formik.errors.password }</FormErrorMessage>
        </FormControl>
      </Stack>
      <Stack direction="row" justifyContent="space-between" mt="15px">
        <Checkbox value={checked} onChange={e=>setChecked(e.target.value)}>记住我</Checkbox>
        <Menu>
          <MenuButton
            as={Text}
            bg="transparent"
            _hover={{color: "#333"}}
            color="#999"
            fontSize="14px"
            fontWeight="normal"
            cursor="pointer"
          >
            登录遇到问题？
          </MenuButton>
          <MenuList>
            <MenuItem _hover={{bg: "#f5f5f5"}} onClick={()=> handleProblem('phone')}>用手机号重置密码</MenuItem>
            <MenuItem _hover={{bg: "#f5f5f5"}} onClick={()=> handleProblem('email')}>用邮箱重置密码</MenuItem>
            <MenuItem _hover={{bg: "#f5f5f5"}} onClick={()=> handleProblem('foreign')}>无法用海外手机登录</MenuItem>
            <MenuItem _hover={{bg: "#f5f5f5"}} onClick={()=> handleProblem('google')}>无法用 Google 账号登录</MenuItem>
          </MenuList>
        </Menu>
      </Stack>
      <Button
        _hover={{ bgColor: '#187cb7' }}
        w="100%"
        bg="#3194d0"
        color="white"
        mt="20px"
        borderRadius="25px"
        h="50px"
        py="4px"
        pr="12px"
        type="submit"
      >
        登录
      </Button>
      <Box mt="50px">
        <Stack direction="row" alignItems="center" justifyContent="space-evenly" mb="10px">
          <Box w="60px" h="1px" bg="#b5b5b5"></Box>
          <Text 
            fontSize="12px" 
            color="#b5b5b5"
            as="h6"
            m="0"
            fontWeight="500"
          >社交账号登录</Text>
          <Box w="60px" h="1px" bg="#b5b5b5"></Box>
        </Stack>
        <Stack direction="row" justifyContent="space-evenly">
          <Image src={WeiboIcon} w="28px" h="28px" cursor="pointer"/>
          <Image src={WechatIcon} w="28px" h="28px" cursor="pointer"/>
          <Image src={QQIcon} w="28px" h="28px" cursor="pointer"/>
        </Stack>
      </Box>
    </form>
  )
}
